package JUC;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 写一个程序，包含两个线程ThreaA,ThreadB.和一个方法recoveryDeadThread
 * 程序运行，A，B线程一定会发生互相死锁.
 * 实现recoveryDeadThread在发生死锁后调用的话，
 * 程序可以解除死锁状态并正常退出.
 */
public class DeadThreadHelp {

    public static void recoveryDeadThread(Thread a,Thread b)  {
        try {
            a.stop();
            System.out.println(1111);
            a.start();
        }catch (Exception e){
//            e.printStackTrace();
            System.out.println(1111);
        }


    }

    public static void main(String[] args) {
        String lockA = "lockA";
        String lockB = "lockB";
        Thread a = new Thread(new MyTask(lockA, lockB), "A");
        Thread b = new Thread(new MyTask(lockB, lockA), "B");
        a.start();
        b.start();

        try {
            Thread.sleep(1000);
            recoveryDeadThread(a,b);
        }catch (Exception e){
//            e.printStackTrace();
        }

    }


}

class MyTask implements Runnable {

    private String lockA;
    private String lockB;

    public MyTask(String lockA, String lockB) {
        this.lockA = lockA;
        this.lockB = lockB;
    }


    @Override
    public void run() {
        synchronized (lockA) {
            while(!Thread.interrupted()){
                System.out.println(Thread.currentThread().getName() + "lock:" + lockA + "=>get" + lockB);
                try {
                    TimeUnit.SECONDS.sleep(2);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (lockB) {
                    System.out.println(Thread.currentThread().getName() + "lock:" + lockB + "=>get" + lockA);
                }
            }

        }
    }
}

class MyTask1 implements Runnable {

    Lock lockA = new ReentrantLock();
    Lock lockB = new ReentrantLock();


    @Override
    public void run() {

        lockA.lock();
        System.out.println("lockA");
        try{
            Thread.sleep(100);
            try {
                lockB.lock();
                System.out.println("lockB");
            }catch (Exception e){
                e.printStackTrace();
            }finally {
                System.out.println("unlockB");
                lockB.unlock();
            }

        }catch (Exception e){
            e.printStackTrace();
        }finally {
            System.out.println("unlockA");
            lockA.unlock();
        }
    }
}